package com.ugoodtech.mdcc.web.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.common.reflect.Reflection;
import com.mysema.query.BooleanBuilder;
import com.mysema.query.types.Path;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.VstarServiceReport.*;
import com.ugoodtech.mdcc.core.dto.ServiceStatChartListResponse;
import com.ugoodtech.mdcc.core.dto.ServiceStatChartResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.ServiceReportService;
import com.ugoodtech.mdcc.core.service.WechatService;
import com.ugoodtech.mdcc.core.utils.SmsServiceUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.SearchParamDTO;
import com.ugoodtech.mdcc.web.pojo.dto.CustomGenerateResultDTO;
import com.ugoodtech.mdcc.web.pojo.vo.StationReportDetailVo;
import com.ugoodtech.mdcc.web.service.AliSmsProvider;
import com.ugoodtech.mdcc.web.service.UserProfileService;
import com.ugoodtech.mdcc.web.service.VstarServiceReportService;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.xpath.operations.Bool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class VstarServiceReportServiceImpl implements VstarServiceReportService {

    private static final Logger logger = LoggerFactory.getLogger(VstarServiceReportServiceImpl.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private CustomReportSmsRepository customReportSmsRepository;

    @Autowired
    private ServiceReportService serviceReportService;
    @Autowired
    private AliSmsProvider aliSmsProvider;
    @Autowired
    private WechatService wechatService;

    private Integer countPerson;

    private List<Station> stationList = new ArrayList<>();

    private List<String[]> otherCustomerStatList = new ArrayList<>();

    private List<String[]> otherCustomerTypeList = new ArrayList<>();

    private List<String[]> otherPaintBrandList = new ArrayList<>();

    private List<String[]> otherMaintainBigProblem = new ArrayList<>();

    private List<String[]> otherStationAppeal = new ArrayList<>();

    private ThreadPoolExecutor smsThreadPool = new ThreadPoolExecutor
        (20, 100, 10, TimeUnit.MINUTES, new LinkedBlockingDeque<Runnable>());

    ///////////////////////////////改////////////////////////////////////////

    private static volatile Converter converter;

    public Converter convert(){
        if (converter == null){
            synchronized (this) {
                if (converter == null) {
                    converter = new Converter();
                }
            }
        }
        return converter;
    }

    //统计常规服务报告
    @Override
    public VstarServiceReport statReport(String provinces, String brand, String category, String name,
                                         Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                         Integer serviceNum, String userName, String isFollowUp, String followType, Long userId, String userType, Boolean isCustomer,
                                         Long customerStat, Long customerType, String paintBrand, String productPosition, String stationNum, Long departmentId) {
        List<StationReport> reports = getStationReport(provinces, brand, category, name, serviceStartTime, serviceEndTime, startTime, endTime, serviceType,
                serviceNum, userName, isFollowUp, followType, userId, userType, isCustomer, customerStat, customerType, paintBrand, productPosition, stationNum, departmentId);
        List<StationReport> reportList = new ArrayList<>();
        for (StationReport stationReport : reports) {
            StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 354L);
            if (null == answer) {
                reportList.add(stationReport);
            }
        }
        otherCustomerStatList = new ArrayList<>();
        otherCustomerTypeList = new ArrayList<>();
        otherPaintBrandList = new ArrayList<>();
        otherMaintainBigProblem = new ArrayList<>();
        otherStationAppeal = new ArrayList<>();
        countPerson = reportList.size();
        stationList = new ArrayList<>();
        logger.info("查出的常规服务报告有：" + countPerson + "份");
        for (StationReport report : reportList) {
            if (stationList.contains(report.getStation())) {
                continue;
            } else {
                stationList.add(report.getStation());
            }
        }
        logger.info("有效的维修站数量为：" + stationList.size() + "个");
        VstarServiceReport vstarServiceReport = new VstarServiceReport();
        vstarServiceReport.setCountPerson(countPerson);
        //销售区域
        vstarServiceReport.setProvinceLsit(getProvinceList(reportList));
        //客户状态
        vstarServiceReport.setCustomerStatList(getCustomerStatList(reportList));
        //其他客户状态
        vstarServiceReport.setOthercustomerStatList(otherCustomerStatList);
        //客户类型
        vstarServiceReport.setCustomerTypeList(getCustomerTypeList(reportList));
        //其他客户类型
        vstarServiceReport.setOtherCustomerTypeList(otherCustomerTypeList);
        //统计维修站
        vstarServiceReport.setVstarServiceReport_serviceType(getServiceType(reportList));
        //统计品牌
        if (StringUtils.isNotEmpty(brand) && StringUtils.isEmpty(category)) {
            Integer IBS = 0;
            Integer BPC = 0;
            Integer FBS = 0;
            Integer DEALERS = 0;
            String[] brandArray = brand.split(",");
            Map<String, Integer> countBrandMap = new HashMap<>();
            List<String[]> brandStr = new ArrayList<>();
            List<String[]> otherBrandArray = new ArrayList<>();
            Map<String, Integer> otherCountBrandMap = new HashMap<>();
            for (StationReport report : reportList) {
                for (String brandName : brandArray) {
                    if (StringUtils.isNotEmpty(brandName)) {
                        if (report.getStation().getCategory().equals(Constants.FOR_S) && report.getStation().getBrand().indexOf(brandName) != -1) {
                            if (countBrandMap.containsKey(brandName)) {
                                Integer value = countBrandMap.get(brandName);
                                countBrandMap.put(brandName, value + 1);
                            } else {
                                countBrandMap.put(brandName, 1);
                            }
                        }
                    }
                }
                if (report.getStation().getCategory().equals(Constants.IBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    IBS += 1;
                }
                if (report.getStation().getCategory().equals(Constants.BPC)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    BPC += 1;
                }
                if (report.getStation().getCategory().equals(Constants.FBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    FBS += 1;
                }
                if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    DEALERS += 1;
                }
            }
            String[] str = new String[2];
            for (Map.Entry<String, Integer> entry : countBrandMap.entrySet()) {
                str = new String[3];
                str[0] = entry.getKey();
                str[1] = entry.getValue().toString();
                str[2] = "";
                brandStr.add(str);
            }
            if (IBS != 0) {
                str = new String[3];
                str[0] = Constants.IBS;
                str[1] = String.valueOf(IBS);
                str[2] = "";
                brandStr.add(str);
            }
            if (BPC != 0) {
                str = new String[3];
                str[0] = Constants.BPC;
                str[1] = String.valueOf(BPC);
                str[2] = "";
                brandStr.add(str);
            }
            if (FBS != 0) {
                str = new String[3];
                str[0] = Constants.FBS;
                str[1] = String.valueOf(FBS);
                str[2] = "";
                brandStr.add(str);
            }
            if (DEALERS != 0) {
                str = new String[3];
                str[0] = Constants.DEALERS;
                str[1] = String.valueOf(DEALERS);
                str[2] = "";
                brandStr.add(str);
            }
            for (Map.Entry<String, Integer> entry : otherCountBrandMap.entrySet()) {
                String[] otherBrand = new String[3];
                otherBrand[0] = entry.getKey();
                otherBrand[1] = entry.getValue().toString();
                otherBrand[2] = "";
                otherBrandArray.add(otherBrand);
            }
            VstarServiceReport_Brand vstarServiceReport_brand = new VstarServiceReport_Brand();
            vstarServiceReport_brand.setBrandArray(brandStr);
            vstarServiceReport_brand.setOtherBrandList(otherBrandArray);
            vstarServiceReport.setVstarServiceReport_brand(vstarServiceReport_brand);
        } else {
            if (StringUtils.isNotEmpty(brand)) {
                String[] brandArray = brand.split(",");
                vstarServiceReport.setVstarServiceReport_brand(getBrand(brandArray, reportList));
            } else {
                vstarServiceReport.setVstarServiceReport_brand(getBrand(null, reportList));
            }

        }

        //油漆品牌
        vstarServiceReport.setPaintBrandList(getPaintBrandList(reportList));
        //其他油漆品牌
        vstarServiceReport.setOtherPaintBrandList(otherPaintBrandList);
        //品牌定位
        vstarServiceReport.setProductPositionList(getProductPositionList(reportList));
        //该维修站目前钣喷维修流程中面对最大问题
        vstarServiceReport.setMaintainBigProblem(getMaintainBigProblemList(reportList));
        //其他该维修站目前钣喷维修流程中面对最大问题
        vstarServiceReport.setOtherMaintainBigProblem(otherMaintainBigProblem);
        //该维修站的主要诉求
        vstarServiceReport.setStationAppeal(getStationAppeal(reportList));
        //其他该维修站的主要诉求
        vstarServiceReport.setOtherStationAppeal(otherStationAppeal);
        //统计服务目标
        vstarServiceReport.setVstarServiceReport_target(getTarget(reportList));
        //统计服务结果
        vstarServiceReport.setVstarServiceReport_results(getResults(reportList));
        return vstarServiceReport;
    }

    public class Converter{
        /**
         * 将常规报告转换为详情
         *
         * @param customerRegularReportList 常规报告关联列表
         * @return 常规报告详情
         */
        public List<StationReportDetailVo> convertToDetail(List<CustomerRegularReport> customerRegularReportList){
            List<StationReportDetailVo> stationReportDetailVoList = new ArrayList<>();
            for (CustomerRegularReport customerRegularReport : customerRegularReportList){
                StationReportDetailVo stationReportDetailVo = new StationReportDetailVo();
                StationReport regularReport = customerRegularReport.getRegularReport();
                Station customer = customerRegularReport.getRegularReport().getStation();
                stationReportDetailVo.setId(customerRegularReport.getRegularReport().getId());
                // 设置工作人员姓名, 是否生成满意度报告, 是否发送短信成功
                UserProfile userProfile = userProfileRepository.findByUserId(regularReport.getUser().getId());
                stationReportDetailVo.setWorkerName(userProfile.getRealName());
                stationReportDetailVo.setIsCustomReportGenerated(customerRegularReport.isEnabled() ? 1 : 0);
                stationReportDetailVo.setIsSmsSended(customerRegularReport.isSended() ? 1 : 0);
                // 设置提交日期, 服务开始时间, 服务结束时间
                stationReportDetailVo.setSubmitDate(customerRegularReport.getCreationTime());
                stationReportDetailVo.setServiceStartTime(regularReport.getStartServiceTime());
                stationReportDetailVo.setServiceEndTime(regularReport.getEndServiceTime());
                // 设置客户代码, 所属省份, 客户名称, 客户状态, 客户类型, 维修站类型, 具体品牌, 油漆品牌
                stationReportDetailVo.setCustomerCode(customer.getStationNum());
                stationReportDetailVo.setProvince(customer.getProvince());
                stationReportDetailVo.setCustomerName(customer.getName());
                stationReportDetailVo.setCustomerStatus(getCustomerStatus(customer.getCustomerStat(), ""));
                stationReportDetailVo.setCustomerType(getCustomerType(customer.getCustomerType(), ""));
                stationReportDetailVo.setStationType(customer.getCategory());
                stationReportDetailVo.setSpecifiedBrand(customer.getBrand());
                stationReportDetailVo.setPaintBrand(getPaintBrand(customer.getPaintBrand()));
                stationReportDetailVo.setBrandPosition(getCommonAnswer(customer.getProductPosition()));
                //获取油漆服务商
                stationReportDetailVo.setServiceProvider(getServiceProvider(customer));
                // 查找该常规报告答案, 设置服务商, 重点工作分类, 服务自我评估
                List<StationRegularServiceReport> stationRegularServiceReportList =
                    stationRegularServiceReportRepository.selectAnswer(regularReport.getId());
                for (StationRegularServiceReport stationRegularServiceReport : stationRegularServiceReportList) {
                    if (157L == stationRegularServiceReport.getQuestionId()) {
                        // 服务自我评估
                        stationReportDetailVo.setSelfComment(stationRegularServiceReport.getAnswerOther());
                    }
                    // 重点工作分类
                    if (155L == stationRegularServiceReport.getQuestionId()){
                        stationReportDetailVo.setWorkDistribution(getServiceContent(stationRegularServiceReport.getAnswerId()));
                    }
                    // 设置联系人姓名, 设置联系人职位, 设置联系人电话
                    if (178L == stationRegularServiceReport.getQuestionId()){
                        stationReportDetailVo.setContactName(stationRegularServiceReport.getAnswerOther());
                    }
                    if (179L == stationRegularServiceReport.getQuestionId()){
                        stationReportDetailVo.setContactPosition(stationRegularServiceReport.getAnswerOther());
                    }
                    if (180L == stationRegularServiceReport.getQuestionId()){
                        stationReportDetailVo.setContactNumber(stationRegularServiceReport.getAnswerOther());
                    }
                }
                stationReportDetailVoList.add(stationReportDetailVo);
            }
            return stationReportDetailVoList;
        }
    }

    private String getServiceProvider(Station station){
        QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationColorReport.deleted.eq(false));
        builder.and(qStationColorReport.enabled.eq(true));
        builder.and(qStationColorReport.questionId.eq(14L));
        builder.and(qStationColorReport.stationReport.station.id.eq(station.getId()));
        StationColorReport colorReport = stationColorReportRepository.findOne(builder);
        return colorReport.getAnswerOther();
    }

    public String getServiceContent(String answer){
       return getCommonAnswer(answer);
    }

    public String getPaintBrand(String paintBrand){
        return getCommonAnswer(paintBrand);
    }

    public String getCommonAnswer(String answer){
        if (answer!=null) {
            String[] answerArray = answer.split(",");
            List<String> answerList = new ArrayList<>();
            for (String singleAnswer : answerArray) {
                QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(singleAnswer));
                if (questionAnswerOption!=null) {
                    answerList.add(questionAnswerOption.getName());
                }
            }
            String answerStr = answerList.toString();
            return answerStr.substring(1, answerStr.length() - 1);
        }else {
            return "";
        }
    }

    public String getCustomerType(Long customerType, String detail){
        if (customerType == 363){
            return "集采客户";
        }
        if (customerType == 364){
            return "非集采客户";
        }
        if (customerType == 365){
            return "经销商（服务商）";
        }
        if (customerType == 366){
            return detail;
        }
        return "";
    }

    public String getCustomerStatus(Long customerType, String detail){
        if (customerType == 359){
            return "现有客户";
        }
        if (customerType == 360){
            return "目标（潜在）客户";
        }
        if (customerType == 361){
            return "丢失客户";
        }
        if (customerType == 362){
            return detail;
        }
        return "";
    }


    /**
     * 分页筛选常规报告, 来生成满意度报告并发送短信
     *
     * @param pageNum 分页索引
     * @param pageSize 分页大小
     * @param searchParamDTO 搜索参数
     */
    public Page listRegularReport(int pageNum, int pageSize, SearchParamDTO searchParamDTO){
        logger.info("Start list regular reports by [{}].", searchParamDTO);
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.regularReport.deleted.eq(false));
        builder.and(qCustomerRegularReport.regularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.regularReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qCustomerRegularReport.regularReport.category.eq(Constants.SERVICE_REPORT));
        // 筛选省份
        if (StringUtils.isNotEmpty(searchParamDTO.getProvinces())) {
            logger.debug("Search provinces [{}].", searchParamDTO.getProvinces());
            String[] province = searchParamDTO.getProvinces().split(",");
            builder.and(qCustomerRegularReport.regularReport.station.province.in(province));
        }
        // 筛选品牌
        if (StringUtils.isNotEmpty(searchParamDTO.getBrandNames())) {
            String[] brandArray = searchParamDTO.getBrandNames().split(",");
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (int i = 0; i < brandArray.length; i++) {
                if (brandArray[i].equals("其他品牌")) {
                    orBuilder.or(qCustomerRegularReport.regularReport.station.otherBrand.eq(true));
                } else {
                    orBuilder.or(qCustomerRegularReport.regularReport.station.brand.like("%" + brandArray[i] + "%"));
                }
            }
            builder.and(orBuilder);
        }
        // 筛选维修站编号
        if (null != searchParamDTO.getStationId()) {
            builder.and(qCustomerRegularReport.regularReport.station.id.eq(searchParamDTO.getStationId()));
        }
        // 筛选维修站类型
        if (StringUtils.isNotEmpty(searchParamDTO.getCategories())) {
            String[] categoryArray = searchParamDTO.getCategories().split(",");
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (String category : categoryArray){
                orBuilder.or(qCustomerRegularReport.regularReport.station.category.like("%" + category + "%"));
            }
            builder.and(orBuilder);
        }
        // 筛选服务类型
        if (StringUtils.isNotEmpty(searchParamDTO.getServiceType())) {
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (String serviceType : searchParamDTO.getServiceType().split(",")){
                orBuilder.or(qCustomerRegularReport.regularReport.serviceTypAnswerIds.like( "%" + serviceType +"%"));
            }
            builder.and(orBuilder);
        }
        // 筛选服务次数
        if (searchParamDTO.getServiceTimes() != null && searchParamDTO.getServiceTimes() != 0) {
            builder.and(qCustomerRegularReport.regularReport.user.serviceNum.eq(searchParamDTO.getServiceTimes()));
        }
        // 筛选客户状态
        if (StringUtils.isNotEmpty(searchParamDTO.getCustomerStats())) {
            builder.and(qCustomerRegularReport.regularReport.station.customerStat.in(
                convertArrayToList(searchParamDTO.getCustomerStats().split(","), Long.class)));
        }
        // 筛选客户类型
        if (StringUtils.isNotEmpty(searchParamDTO.getCustomerTypes())) {
            builder.and(qCustomerRegularReport.regularReport.station.customerType.in(
                convertArrayToList(searchParamDTO.getCustomerTypes().split(","), Long.class)));
        }
        // 筛选油漆品牌
        if (StringUtils.isNotEmpty(searchParamDTO.getPaintBrands())) {
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (String paintBrand : searchParamDTO.getPaintBrands().split(",")){
                orBuilder.or(qCustomerRegularReport.regularReport.station.paintBrand.like( "%" + paintBrand +"%"));
            }
            builder.and(orBuilder);
        }
        // 筛选品牌定位
        if (StringUtils.isNotEmpty(searchParamDTO.getProductPositions())) {
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (String productPosition : searchParamDTO.getProductPositions().split(",")){
                orBuilder.or(qCustomerRegularReport.regularReport.station.productPosition.like("%" + productPosition + "%"));
            }
            builder.and(orBuilder);
        }
        // 筛选满意度分数
        if (StringUtils.isNoneEmpty(searchParamDTO.getScores())){
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (String score : searchParamDTO.getScores().split(",")) {
                String[] str = new String[61];
                for (int i = 0; i < str.length; i++) {
                    str[i] = i + "";
                }
                String[] notStr = new String[39];
                int index = 61;
                for (int i = 0; i < 39; i++) {
                    notStr[i] = index + "";
                    index += 1;
                }
                if (StringUtils.isNotEmpty(score)) {
                    if (score.equals(Constants.FULL_MARKS)) {
                        orBuilder.or(qCustomerRegularReport.score.eq("100"));
                    }
                    if (score.equals(Constants.MORE_THAN_SIXTY)) {
                        orBuilder.or(qCustomerRegularReport.score.in(notStr));
                    }
                    if (score.equals(Constants.BELOW_THAN_SIXTY)) {
                        orBuilder.or(qCustomerRegularReport.score.in(str));
                    }
                }
            }
            builder.and(orBuilder);

        }
        // 筛选工作人员名称和部门, 然后找出用户, 筛选这些用户的常规报告
        Set<Long> userIds = new HashSet<>();
        if (searchParamDTO.getUserId() != null) {
            userIds.add(searchParamDTO.getUserId());
        } else {
            // 筛选部门
            if (StringUtils.isNotEmpty(searchParamDTO.getDepartmentIds())) {
                List<Long> departmentIdList = convertArrayToList(searchParamDTO.getDepartmentIds().split(","), Long.class);
                for (Long departmentId : departmentIdList) {
                    // 部门是经销商, 则找出所有的用户, 筛选这些用户的常规报告
                    if (searchParamDTO.getDepartmentIds().equals(27L)) {
                        QUser qUser = QUser.user;
                        BooleanBuilder booleanBuilder = new BooleanBuilder();
                        booleanBuilder.and(qUser.deleted.eq(false));
                        booleanBuilder.and(qUser.enabled.eq(true));
                        booleanBuilder.and(qUser.userType.eq(UserType.dealers));
                        List<User> userList = (List<User>) userRepository.findAll(booleanBuilder);
                        for (User u : userList) {
                            userIds.add(u.getId());
                        }
                    } else {
                        // 先看是不是父部门, 看父部门的所有部门, 然后找出这些部门下的人
                        QUserProfile qUserProfile = QUserProfile.userProfile;
                        BooleanBuilder booleanBuilder = new BooleanBuilder();
                        booleanBuilder.and(qUserProfile.deleted.eq(false));
                        booleanBuilder.and(qUserProfile.enabled.eq(true));
                        List<Department> departmentList = departmentRepository
                            .selectParentDeparmentL(departmentId);
                        if (CollectionUtils.isNotEmpty(departmentList)) {
                            List<Long> departmentIds = new ArrayList<>();
                            for (Department department : departmentList) {
                                departmentIds.add(department.getId());
                            }
                            booleanBuilder
                                .and(qUserProfile.departmentList.any().id.in(departmentIds));
                        } else {
                            booleanBuilder.and(qUserProfile.departmentList.any().id
                                .eq(departmentId));
                        }
                        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository
                            .findAll(booleanBuilder);
                        for (UserProfile profile : userProfileList) {
                            userIds.add(profile.getUser().getId());
                        }
                    }
                }
            }
        }
        // 根据用户筛选出常规报告
        if (!userIds.isEmpty()) {
            builder.and(qCustomerRegularReport.regularReport.user.id.in(userIds));
        }
        // 筛选服务开始结束时间
        if (searchParamDTO.getServiceStartTime() != null && searchParamDTO.getServiceStartTime() != 0
            && searchParamDTO.getServiceEndTime() != null && searchParamDTO.getServiceEndTime() != 0) {
            builder.and(qCustomerRegularReport.regularReport.startServiceTime.after(new Date(searchParamDTO.getServiceStartTime())));
            builder.and(qCustomerRegularReport.regularReport.endServiceTime.before(new Date(searchParamDTO.getServiceEndTime())));
        }
        // 筛选报告提交时间段
        if (searchParamDTO.getStartTime() != null && searchParamDTO.getStartTime() != 0
            && searchParamDTO.getEndTime() != null && searchParamDTO.getEndTime() != 0) {
            builder.and(qCustomerRegularReport.regularReport.creationTime.after(new Date(searchParamDTO.getStartTime())));
            builder.and(qCustomerRegularReport.regularReport.creationTime.before(new Date(searchParamDTO.getEndTime())));
        }
        // 设置是否跟进
        if (searchParamDTO.getIsFollowUp() != 2){
            builder.and(qCustomerRegularReport.regularReport.isfollowed.eq(searchParamDTO.getIsFollowUp() == 1));
        }
        // 筛选是否填写满意度报告, 若关联表中没有相应满意度报告记录则去掉该常规报告
        if (searchParamDTO.getIsCustomer() != 2){
            builder.and(qCustomerRegularReport.type.eq(searchParamDTO.getIsCustomer() == 1));
        }

        // 筛选是否生成了满意度报告, 除0, 1的条件视为全部
        if(searchParamDTO.getIsCustomReportGenerated() == null
            || (searchParamDTO.getIsCustomReportGenerated() != null && searchParamDTO.getIsCustomReportGenerated() == 0)){
            builder.and(qCustomerRegularReport.enabled.eq(false));
        }
        else if (searchParamDTO.getIsCustomReportGenerated() == 1){
            builder.and(qCustomerRegularReport.enabled.eq(true));
        }
        // 找出符合条件的满意度报告
        Sort sort = new Sort(Direction.DESC, "creationTime");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page page = customerRegularReportRepository.findAll(builder, pageable);
        return new PageImpl(convert().convertToDetail(page.getContent()), pageable, page.getTotalElements());

    }

    /**
     * 将字符串数组的值转换为相应类的列表
     *
     * @param array 字符串数组
     * @param elementClass 数组元素要转换成的类型
     * @return 转换后的列表
     */
    private <T> List<T> convertArrayToList(String[] array, Class<T> elementClass){
        List<T> list = new ArrayList<>();
        if (Integer.class.equals(elementClass)){
            for (String object : array){
                list.add((T)Integer.valueOf(object));
            }
        }
        else if(Long.class.equals(elementClass)){
            for (String object : array){
                list.add((T)Long.valueOf(object));
            }
        }
        return list;
    }

    /**
     * 根据馋鬼报告id列表发送短信
     *
     * @param idList 常规报告id列表
     */
    public CustomGenerateResultDTO generateCustomReport(List<Long> idList){
        // 查找这些常规报告id的列表
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
//        builder.and(qStationReport.deleted.eq(false));
//        builder.and(qStationReport.enabled.eq(true));
//        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
//        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.id.in(idList));
        List<StationReport> stationReportList = (List<StationReport>)stationReportRepository.findAll(builder);
        // 生成满意度报告失败
        Set<String> errorUserSet = new HashSet<>(20);
        // 生成满意度报告成功, 短信发送成功
        Set<String> successUserSet = new HashSet<>(20);
        // 生成满意度报告成功, 短信发送失败
        Set<String> successSmsErrorUserSet = new HashSet<>(20);
        // 生成满意度报告发短信重复
        Set<String> duplicateUserSet = new HashSet<>(20);
        // 短信发送失败
        Set<String> smsSendErrorUserSet = new HashSet<>(20);
        // 短信发送成功
        Set<String> smsSendSuccessUserSet = new HashSet<>(20);
        // 筛选之前生成满意度报告成功的id, 用于后续分别发短信的结果是由哪种情况下发的
        Set<Long> smsSendedIdSet = new HashSet<>(20);
        Map<CustomerRegularReport, Future<SendSmsResponse>> smsSendingResultMap = new HashMap<>();
        for (StationReport stationReport : stationReportList){
            stationReport.setImprovementTime(1L);
            stationReportRepository.save(stationReport);
            // 生成满意度报告, 先查找该常规报告的关联信息并将其启用
            CustomerRegularReport customerRegularReport = customerRegularReportRepository
                .findByRegularReportIdNoCheckEnable(stationReport.getId());
            // 获取用户信息
            UserProfile userProfile = userProfileRepository.findByUserId(customerRegularReport.getRegularReport().getUser().getId());
            // 将之前生成过满意度报告成功, 但是短信发送失败的筛选出来
            if (customerRegularReport.isEnabled()){
                // 筛选重复生成的满意度报告
                if (customerRegularReport.isSended()) {
                    duplicateUserSet.add(userProfile.getRealName());
                }
                else {
                    smsSendedIdSet.add(customerRegularReport.getId());
                }
            }
            // 启用满意度报告
            customerRegularReport.setEnabled(true);
            logger.info("User of custom report generated are [{}].", smsSendedIdSet);
            if (customerRegularReportRepository.save(customerRegularReport).isEnabled()) {
                if (!customerRegularReport.isSended()) {
                    smsSendingResultMap
                        .put(customerRegularReport, sendCustomReportSms(stationReport));
                }
            }
            else {
                errorUserSet.add(userProfile.getRealName());
            }
        }
        // 设置短信发送成功标志
        for (Entry<CustomerRegularReport, Future<SendSmsResponse>> sendSmsResult : smsSendingResultMap.entrySet()){
            // 筛选生成满意度报告成功和失败的人员
            CustomerRegularReport customerRegularReport = sendSmsResult.getKey();
            // 获取用户信息
            UserProfile userProfile = userProfileRepository.findByUserId(customerRegularReport.getRegularReport().getUser().getId());
            try {
                if (checkSmsSendResult(sendSmsResult.getValue().get())) {
                    // 添加发送短信记录
                    addSmsSendRecord(customerRegularReport.getId());
                    if (smsSendedIdSet.contains(customerRegularReport.getId())){
                        smsSendSuccessUserSet.add(userProfile.getRealName());
                    }
                    else {
                        successUserSet.add(userProfile.getRealName());
                    }
                    customerRegularReport.setSended(true);
                } else {
                    if (smsSendedIdSet.contains(customerRegularReport.getId())){
                        smsSendErrorUserSet.add(userProfile.getRealName());
                    }
                    else {
                        successSmsErrorUserSet.add(userProfile.getRealName());
                    }
                    customerRegularReport.setSended(false);
                }
            }
            catch (Exception ex){
                logger.warn(ex.getMessage());
                if (smsSendedIdSet.contains(customerRegularReport.getId())){
                    smsSendErrorUserSet.add(userProfile.getRealName());
                }
                else {
                    successSmsErrorUserSet.add(userProfile.getRealName());
                }
                customerRegularReport.setSended(false);
            }
            customerRegularReportRepository.save(customerRegularReport);
        }
        logger.info("User Sets are errorUserSet [{}], "
                + "successUserSet [{}], "
                + "duplicateUserSet [{}], "
                + "smsSendErrorUserSet [{}], "
                + "successSmsErrorUserSet [{}], "
                + "smsSendSuccessUserSet [{}].",
            errorUserSet, successUserSet, duplicateUserSet, smsSendErrorUserSet, successSmsErrorUserSet, smsSendSuccessUserSet);
        return CustomGenerateResultDTO.builder()
            .errorUserSet(errorUserSet)
            .successUserSet(successUserSet)
            .duplicateUserSet(duplicateUserSet)
            .smsSendErrorUserSet(smsSendErrorUserSet)
            .successSmsErrorUserSet(successSmsErrorUserSet)
            .smsSendSuccessUserSet(smsSendSuccessUserSet)
            .build();
    }

    private void addSmsSendRecord(Long customReportId){
        CustomReportSms customReportSms = new CustomReportSms();
        customReportSms.setCreateTime(new Date());
        customReportSms.setSendTime(new Date());
        customReportSms.setCustomReportId(customReportId);
        customReportSms.setUpdateTime(new Date());
        customReportSmsRepository.save(customReportSms);
    }

    private Future sendCustomReportSms(final StationReport stationReport){
        // 查找该常规报告的答案
        QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReport.deleted.eq(false));
        builder.and(qStationRegularServiceReport.enabled.eq(true));
        builder.and(qStationRegularServiceReport.stationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationRegularServiceReport.stationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationRegularServiceReport.stationReport.id.eq(stationReport.getId()));
        List<StationRegularServiceReport> stationRegularServiceReportList = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builder);
        // 根据答案找出服务内容
        String serviceTypeStr = "";
        for (StationRegularServiceReport answer : stationRegularServiceReportList) {
            if (answer.getQuestionId() == 155L) {
                serviceTypeStr = answer.getAnswerId();
                break;
            }
        }
        // 拼接服务内容
        StringBuffer stringBuffer = new StringBuffer();
        if (StringUtils.isNotEmpty(serviceTypeStr)) {
            String[] str = serviceTypeStr.split(",");
            for (String s : str) {
                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(s));
                if (answerOption.getId().equals(191L)) {
                    stringBuffer = new StringBuffer("漆星服务");
                    break;
                }
                stringBuffer.append(answerOption.getName() + ",");
            }
        }
        String firstData = "您好，在" + stationReport.getStation().getName() + "进行的" + stringBuffer.toString() + "已完成";

        final StringBuffer finalStringBuffer = stringBuffer;
        final UserProfile userProfile = userProfileRepository.findByUserId(stationReport.getUser().getId());
        User contactUser = userRepository.findByUserName_phone(stationReport.getContactUser());
        wechatService.pushWechatMessage(
            contactUser, "Ujk2bjdBKx3vU1IjSH3OyD84rgF0Hz-oU2Ds564DW2I",
            Constants.WECHAT_PUSH_URL, firstData,
            "请登录漆星服务公众号对Ta的本次服务进行打分", userProfile.getRealName(), stationReport.getUpdateTimeStr(), "", "", "");
        logger.info("Sending sms parameters are [{}], [{}], [{}], [{}], [{}]",
            stationReport.getContactUser(),
            userProfile.getRealName(),
            stationReport.getUpdateTime(),
            stationReport.getStation().getName(),
            finalStringBuffer.toString());
        // 发送满意度报告填写提醒短信
        return smsThreadPool.submit(new Callable<SendSmsResponse>() {
            @Override
            public SendSmsResponse call() throws Exception {
                return aliSmsProvider.sendCustomerWriteMsg(stationReport.getContactUser(),
                    userProfile.getRealName(),
                    DateFormatUtils.format(stationReport.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"),
                    stationReport.getStation().getName(),
                    finalStringBuffer.length() > 17 ? finalStringBuffer.substring(0,17) + "..." : finalStringBuffer.toString());
            }
        });
    }

    public boolean checkSmsSendResult(SendSmsResponse sendSmsResponse){
        logger.info("Send sms result is [{}], [{}].", sendSmsResponse.getCode(), sendSmsResponse.getMessage());
        if ("OK".equals(sendSmsResponse.getCode()) && Objects.equals("OK", sendSmsResponse.getMessage())){
            return true;
        }
        return false;
    }

    //将Map转List
    private List<String[]> toListStringArray(Map<String, Integer> map) {
        List<String[]> strList = new ArrayList<>();
        String[] str = new String[3];
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            str = new String[3];
            str[0] = entry.getKey();
            str[1] = entry.getValue().toString();
            str[2] = "";
            strList.add(str);
        }
        return strList;
    }

    private String getStationColorReport_AnswerOther(StationReport stationReport, Long questionId) {
        if (stationReport.getStation() != null && stationReport.getStation().getId() != null && stationReport.getStation().getId() != 0) {
            Long stationId = stationReport.getStation().getId();
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(stationId));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            StationReport report = stationReportRepository.findOne(builder);
            if (report == null) {
                return null;
            }
            StationColorReport colorReport = stationColorReportRepository.selectReport(report.getId(), questionId);
            if (colorReport != null && StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
                return colorReport.getAnswerOther();
            }
        }
        return null;
    }

    //销售区域
    private List<String[]> getProvinceList(List<StationReport> reportList) {
        Map<String, Integer> provinceMap = new HashMap<>();
        for (StationReport stationReport : reportList) {
            if (StringUtils.isNotEmpty(stationReport.getStation().getProvince())) {
                String province = stationReport.getStation().getProvince();
                if (provinceMap.containsKey(province)) {
                    Integer value = provinceMap.get(province);
                    provinceMap.put(province, value + 1);
                } else {
                    provinceMap.put(province, 1);
                }
            }
        }
        return toListStringArray(provinceMap);
    }

    //客户状态
    private List<String[]> getCustomerStatList(List<StationReport> reportList) {
        Map<String, Integer> customerStatMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reportList) {
            if (report.getStation().getCustomerStat() != null && report.getStation().getCustomerStat() != 0) {
                Long customerStatId = report.getStation().getCustomerStat();
                answerOption = questionAnswerOptionRepository.findOne(customerStatId);
                if (answerOption != null) {
                    if (customerStatMap.containsKey(answerOption.getName())) {
                        Integer value = customerStatMap.get(answerOption.getName());
                        customerStatMap.put(answerOption.getName(), value + 1);
                    } else {
                        customerStatMap.put(answerOption.getName(), 1);
                    }
                }
                if (customerStatId == 362L) {
                    // todo 其他客户状态
                    String answer = getStationColorReport_AnswerOther(report, 184L);
                    if (answer == null) {
                        continue;
                    }
                    if (otherMap.containsKey(answer)) {
                        Integer value = otherMap.get(answer);
                        otherMap.put(answer, value + 1);
                    } else {
                        otherMap.put(answer, 1);
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherCustomerStatList = toListStringArray(otherMap);
        }
        return toListStringArray(customerStatMap);
    }

    //客户类型
    private List<String[]> getCustomerTypeList(List<StationReport> reportList) {
        Map<String, Integer> customerTypeMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reportList) {
            if (report.getStation().getCustomerType() != null && report.getStation().getCustomerType() != 0) {
                Long customerTypeId = report.getStation().getCustomerType();
                answerOption = questionAnswerOptionRepository.findOne(customerTypeId);
                if (customerTypeMap.containsKey(answerOption.getName())) {
                    Integer value = customerTypeMap.get(answerOption.getName());
                    customerTypeMap.put(answerOption.getName(), value + 1);
                } else {
                    customerTypeMap.put(answerOption.getName(), 1);
                }
                if (customerTypeId == 366L) {
                    // todo 其他客户类型
                    String answer = getStationColorReport_AnswerOther(report, 185L);
                    if (answer == null) {
                        continue;
                    }
                    if (otherMap.containsKey(answer)) {
                        Integer value = otherMap.get(answer);
                        otherMap.put(answer, value + 1);
                    } else {
                        otherMap.put(answer, 1);
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherCustomerTypeList = toListStringArray(otherMap);
        }
        return toListStringArray(customerTypeMap);
    }

    //油漆品牌
    private List<String[]> getPaintBrandList(List<StationReport> reportList) {
        Map<String, Integer> paintBrandMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reportList) {
            if (StringUtils.isNotEmpty(report.getStation().getPaintBrand())) {
                String[] paintBrandids = report.getStation().getPaintBrand().split(",");
                for (String id : paintBrandids) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption!=null && answerOption.getName() != null) {
                        if (paintBrandMap.containsKey(answerOption.getName())) {
                            Integer value = paintBrandMap.get(answerOption.getName());
                            paintBrandMap.put(answerOption.getName(), value + 1);
                        } else {
                            paintBrandMap.put(answerOption.getName(), 1);
                        }
                    }
                    if (id.equals("280")) {
                        //todo 其他的油漆品牌
                        String answer = getStationColorReport_AnswerOther(report, 13L);
                        if (answer == null) {
                            continue;
                        }
                        if (otherMap.containsKey(answer)) {
                            Integer value = otherMap.get(answer);
                            otherMap.put(answer, value + 1);
                        } else {
                            otherMap.put(answer, 1);
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherPaintBrandList = toListStringArray(otherMap);
        }
        return toListStringArray(paintBrandMap);
    }

    //品牌定位
    private List<String[]> getProductPositionList(List<StationReport> reportList) {
        Map<String, Integer> productPositionMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reportList) {
            if (StringUtils.isNotEmpty(report.getStation().getProductPosition())) {
                String[] productPositionids = report.getStation().getProductPosition().split(",");
                for (String id : productPositionids) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption!=null && answerOption.getName() != null) {
                        if (productPositionMap.containsKey(answerOption.getName())) {
                            Integer value = productPositionMap.get(answerOption.getName());
                            productPositionMap.put(answerOption.getName(), value + 1);
                        } else {
                            productPositionMap.put(answerOption.getName(), 1);
                        }
                    }
                }
            }
        }
        return toListStringArray(productPositionMap);
    }

    //目前颜色准确度
    private List<String[]> getColorAccuracyList(List<StationReport> reportList) {
        Map<String, Integer> colorAccuracyMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reportList) {
            // todo 目前颜色准确度
        }
        return null;
    }

    //维修站目前钣喷维修流程中面对最大问题
    private List<String[]> getMaintainBigProblemList(List<StationReport> reportList) {
        Map<String, Integer> maintainBigProblemMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        StationColorReport stationColorReport = null;
        for (StationReport report : reportList) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReport.auditing.eq(Constants.AUDIT_TRUE));
            builder.and(qStationReport.station.id.eq(report.getStation().getId()));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                logger.info("ID为：" + report.getStation().getId() + "的维修站没有基础报告");
                continue;
            }
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 56L);
            if (stationColorReport != null && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                String[] problemIds = stationColorReport.getAnswerId().split(",");
                for (String id : problemIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(Long.valueOf(id)));
                        if (maintainBigProblemMap.containsKey(answerOption.getName())) {
                            Integer value = maintainBigProblemMap.get(answerOption.getName());
                            maintainBigProblemMap.put(answerOption.getName(), value + 1);
                        } else {
                            maintainBigProblemMap.put(answerOption.getName(), 1);
                        }
                        if (id.equals("266")) {
                            // todo 其他面对最大问题
                            String answer = getStationColorReport_AnswerOther(stationReport, 56L);
                            if (answer == null) {
                                continue;
                            }
                            if (otherMap.containsKey(answer)) {
                                Integer value = otherMap.get(answer);
                                otherMap.put(answer, value + 1);
                            } else {
                                otherMap.put(answer, 1);
                            }
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherMaintainBigProblem = toListStringArray(otherMap);
        }
        return toListStringArray(maintainBigProblemMap);
    }

    //维修站的主要诉求
    private List<String[]> getStationAppeal(List<StationReport> reportList) {
        Map<String, Integer> stationAppealMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        StationColorReport stationColorReport = null;
        for (StationReport report : reportList) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReport.auditing.eq(Constants.AUDIT_TRUE));
            builder.and(qStationReport.station.id.eq(report.getStation().getId()));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                logger.info("ID为：" + report.getStation().getId() + "的维修站没有基础报告");
                continue;
            }
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 59L);
            if (stationColorReport != null && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                String[] appealIds = stationColorReport.getAnswerId().split(",");
                for (String id : appealIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(Long.valueOf(id)));
                        if (stationAppealMap.containsKey(answerOption.getName())) {
                            Integer value = stationAppealMap.get(answerOption.getName());
                            stationAppealMap.put(answerOption.getName(), value + 1);
                        } else {
                            stationAppealMap.put(answerOption.getName(), 1);
                        }
                        if (id.equals("272")) {
                            // todo 其他主要诉求
                            String answer = getStationColorReport_AnswerOther(stationReport, 59L);
                            if (answer == null) {
                                continue;
                            }
                            if (otherMap.containsKey(answer)) {
                                Integer value = otherMap.get(answer);
                                otherMap.put(answer, value + 1);
                            } else {
                                otherMap.put(answer, 1);
                            }
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherStationAppeal = toListStringArray(otherMap);
        }
        return toListStringArray(stationAppealMap);
    }


    //统计维修站类型
    private VstarServiceReport_ServiceType getServiceType(List<StationReport> reportList) {
        VstarServiceReport_ServiceType serviceType = new VstarServiceReport_ServiceType();
        Long BPC = 0L;
        Long FBS = 0L;
        Long fourS = 0L;
        Long IBS = 0L;
        Long DEALERS = 0L;
        for (StationReport report : reportList) {
            if (report.getStation().getCategory().equals(Constants.BPC)) {
                BPC += 1;
            }
            if (report.getStation().getCategory().equals(Constants.FBS)) {
                FBS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.FOR_S)) {
                fourS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.IBS)) {
                IBS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                DEALERS += 1;
            }
        }
        serviceType.setBPC(BPC.intValue());
        serviceType.setFBS(FBS.intValue());
        serviceType.setFourS(fourS.intValue());
        serviceType.setIBS(IBS.intValue());
        serviceType.setDEALERS(DEALERS.intValue());
        serviceType.setCountPerson(BPC.intValue() + FBS.intValue() + fourS.intValue() + IBS.intValue() + DEALERS.intValue());
        return serviceType;
    }


    //统计品牌
    private VstarServiceReport_Brand getBrand(String[] brandArray, List<StationReport> reportList) {
        List<String> brandNames = new ArrayList<>();
        for (StationReport report : reportList) {
            if (report.getStation().getCategory().equals(Constants.FOR_S)) {
                String[] brandName = report.getStation().getBrand().split(",");
                for (String brand : brandName) {
                    if (brandArray != null) {
                        for (String str : brandArray) {
                            if (!brand.equals(str)) {
                                continue;
                            } else {
                                if (StringUtils.isNotEmpty(brand)) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    } else {
                        if (StringUtils.isNotEmpty(brand)) {
                            brandNames.add(brand);
                        }
                    }
                }
            } else {
                if (report.getStation().getCategory().equals(Constants.IBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.IBS);
                }
                if (report.getStation().getCategory().equals(Constants.BPC)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.BPC);
                }
                if (report.getStation().getCategory().equals(Constants.FBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.FBS);
                }
                if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.DEALERS);
                }
            }
        }
        return countBrand(brandNames);
    }

    private VstarServiceReport_Brand countBrand(List<String> brandNames) {
        Map<String, Integer> brandMap = new HashMap<>();
        for (String brand : brandNames) {
            if (brandMap.containsKey(brand)) {
                Integer value = brandMap.get(brand);
                brandMap.put(brand, value + 1);
            } else {
                brandMap.put(brand, 1);
            }
        }
        VstarServiceReport_Brand brand = new VstarServiceReport_Brand();
        List<String[]> brandList = new ArrayList<>();
        List<String[]> otherBrandList = new ArrayList<>();
        Map<String, Integer> otherbrandMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : brandMap.entrySet()) {
            if (entry.getKey().equals(Constants.IBS) || entry.getKey().equals(Constants.FBS) || entry.getKey().equals(Constants.BPC)) {
                continue;
            }
            String[] brandArray = new String[3];
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(entry.getKey());
            if (answerOption != null) {
                brandArray[0] = entry.getKey();
                brandArray[1] = entry.getValue().toString();
                brandArray[2] = "";
                brandList.add(brandArray);
            } else {
                if (otherbrandMap.containsKey("其他品牌")) {
                    Integer value = otherbrandMap.get("其他品牌");
                    otherbrandMap.put("其他品牌", value + entry.getValue());
                } else {
                    otherbrandMap.put("其他品牌", entry.getValue());
                }
                String[] otherBrandArray = new String[3];
                otherBrandArray[0] = entry.getKey();
                otherBrandArray[1] = entry.getValue() + "";
                otherBrandArray[2] = "";
                otherBrandList.add(otherBrandArray);
            }
        }
        for (Map.Entry<String, Integer> entry : brandMap.entrySet()) {
            if (entry.getKey().equals(Constants.IBS) || entry.getKey().equals(Constants.FBS) || entry.getKey().equals(Constants.BPC)) {
                String[] otherBrand = new String[3];
                otherBrand[0] = entry.getKey();
                otherBrand[1] = entry.getValue().toString();
                otherBrand[2] = "";
                brandList.add(otherBrand);
            }
        }
        if (otherbrandMap != null && !otherbrandMap.isEmpty()) {
            String[] otherBrand = new String[3];
            otherBrand[0] = "其他品牌";
            otherBrand[1] = otherbrandMap.get("其他品牌").toString();
            otherBrand[2] = "";
            brandList.add(otherBrand);
        }
        brand.setOtherBrandList(otherBrandList);
        brand.setBrandArray(brandList);
        brand.setCountPerson(countPerson);
        return brand;
    }


    //统计服务目标
    private VstarServiceReport_Target getTarget(List<StationReport> reports) {
        List<String> targetIdList = new ArrayList<>();
        List<StationReport> reportList = new ArrayList<>();
        for (StationReport report : reports) {
            String[] targetIds = report.getServiceTypAnswerIds().split(",");
            for (String target : targetIds) {
                if (StringUtils.isNotEmpty(target)) {
                    targetIdList.add(target);
                    if (target.equals("191")) {
                        reportList.add(report);
                    }
                }
            }
        }
        VstarServiceReport_Target targetList = countTarget(targetIdList);
        targetList.setOtherTarget(targetOther(reportList));
        return targetList;
    }

    private VstarServiceReport_Target countTarget(List<String> targetIdList) {
        Map<Long, Integer> targetMap = new HashMap<>();
        for (String target : targetIdList) {
            if (targetMap.containsKey(Long.valueOf(target))) {
                Integer value = targetMap.get(Long.valueOf(target));
                targetMap.put(Long.valueOf(target), value + 1);
            } else {
                targetMap.put(Long.valueOf(target), 1);
            }
        }
        VstarServiceReport_Target target = new VstarServiceReport_Target();
        List<String[]> targetList = new ArrayList<>();
        for (Map.Entry<Long, Integer> entry : targetMap.entrySet()) {
            String[] targetArray = new String[3];
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(entry.getKey());
            if (answerOption != null) {
                targetArray[0] = answerOption.getName();
                targetArray[1] = entry.getValue().toString();
                targetArray[2] = "";
                targetList.add(targetArray);
            }
        }
        target.setTarget(targetList);
        target.setCountPerson(countPerson);
        return target;
    }

    private List<String[]> targetOther(List<StationReport> reportList) {
        List<String[]> otherTargerList = new ArrayList<>();
        for (StationReport report : reportList) {
//            if (report.getServiceTypAnswerIds().indexOf("191") == -1) {
//                continue;
//            }
            StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.selectQuestionOther(report.getId(), 155L);
            if (serviceReport == null) {
                continue;
            }
            String realName = "";
            if (report.getUser() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
                if (userProfile != null) {
                    if (StringUtils.isNotEmpty(userProfile.getRealName())) {
                        realName = userProfile.getRealName();
                    }
                }
            }
            String[] otherTarger = new String[6];
            otherTarger[0] = report.getStation().getName();
            otherTarger[1] = report.getStation().getStationNum();
            otherTarger[2] = report.getCreationTimeStr();
            otherTarger[3] = serviceReport.getAnswerOther();
            otherTarger[4] = realName;
            otherTarger[5] = "";
            otherTargerList.add(otherTarger);
        }
        return otherTargerList;
    }

    //统计服务结果
    private VstarServiceReport_Results getResults(List<StationReport> reports) {
        VstarServiceReport_Results results = new VstarServiceReport_Results();
        Long noComplete_UnableToFollowUp = 0L;
        Long noComplete_NeedToFollowUp = 0L;
        Long complete = 0L;
        Long complete_NeedOthersToFollowUp = 0L;
        for (StationReport report : reports) {
            noComplete_UnableToFollowUp += (Long) stationRegularServiceReportRepository.count(179L, report.getId());
            noComplete_NeedToFollowUp += (Long) stationRegularServiceReportRepository.count(180L, report.getId());
            complete += (Long) stationRegularServiceReportRepository.count(181L, report.getId());
            complete_NeedOthersToFollowUp += (Long) stationRegularServiceReportRepository.count(182L, report.getId());
        }
        List<VstarServiceReport_CompleteFollowUp> completeFollowUps = new ArrayList<>();
        List<VstarServiceReport_UnFinshedNoFollowUp> unFinshedNoFollowUps = new ArrayList<>();
        List<VstarServiceReport_UnFinshedFollowUp> unFinshedFollowUps = new ArrayList<>();

        List<String[]> noComplete_UnFollowUp = new ArrayList<>();
        List<String[]> noComplete_needFollowUp = new ArrayList<>();
        List<String[]> completeReport = new ArrayList<>();
        List<String[]> complete_needFollowUp = new ArrayList<>();
        List<String[]> manageProduct = new ArrayList<>();
        List<String[]> planReport = new ArrayList<>();

        for (StationReport report : reports) {
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            QStationRegularServiceReport regularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(regularServiceReport.deleted.eq(false));
            builder.and(regularServiceReport.stationReport.id.eq(report.getId()));
            builder.and(regularServiceReport.questionId.eq(156L));
//            builder.and(regularServiceReport.answerId.ne("181"));
            StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.findOne(builder);
            if (serviceReport != null) {
                //没有完成，无法后续跟进
                if (Long.valueOf(serviceReport.getAnswerId()).equals(179L)) {
                    String[] str = getStrArray(report, userProfile);
                    noComplete_UnFollowUp.add(str);

                    VstarServiceReport_CompleteFollowUp completeFollowUp = new VstarServiceReport_CompleteFollowUp();
                    completeFollowUp.setStationName(report.getStation().getName());
                    completeFollowUp.setStationNum(report.getStation().getStationNum());
                    completeFollowUp.setCreateTime(report.getCreationTimeStr());
                    completeFollowUp.setId(report.getId());
                    completeFollowUp.setUserName(userProfile.getRealName());
                    completeFollowUp.setAnswer(serviceReport.getAnswerOther());
                    completeFollowUps.add(completeFollowUp);
                }
                //没有完成，需后续跟进
                if (Long.valueOf(serviceReport.getAnswerId()).equals(180L)) {
                    String[] str = getStrArray(report, userProfile);
                    noComplete_needFollowUp.add(str);

                    VstarServiceReport_UnFinshedNoFollowUp unFinshedNoFollowUp = new VstarServiceReport_UnFinshedNoFollowUp();
                    unFinshedNoFollowUp.setStationName(report.getStation().getName());
                    unFinshedNoFollowUp.setStationNum(report.getStation().getStationNum());
                    unFinshedNoFollowUp.setCreateTime(report.getCreationTimeStr());
                    unFinshedNoFollowUp.setId(report.getId());
                    unFinshedNoFollowUp.setUserName(userProfile.getRealName());
                    unFinshedNoFollowUp.setAnswer(serviceReport.getAnswerOther());
                    unFinshedNoFollowUps.add(unFinshedNoFollowUp);
                }
                //已完成
                if (Long.valueOf(serviceReport.getAnswerId()).equals(181L)) {
                    String[] str = getStrArray(report, userProfile);
                    completeReport.add(str);
                }
                //已完成，但需其他部门跟进
                if (Long.valueOf(serviceReport.getAnswerId()).equals(182L)) {
                    String[] str = getStrArray(report, userProfile);
                    complete_needFollowUp.add(str);

                    VstarServiceReport_UnFinshedFollowUp unFinshedFollowUp = new VstarServiceReport_UnFinshedFollowUp();
                    unFinshedFollowUp.setStationName(report.getStation().getName());
                    unFinshedFollowUp.setStationNum(report.getStation().getStationNum());
                    unFinshedFollowUp.setCreateTime(report.getCreationTimeStr());
                    unFinshedFollowUp.setId(report.getId());
                    if (userProfile != null) {
                        unFinshedFollowUp.setUserName(userProfile.getRealName());
                    } else {
                        unFinshedFollowUp.setUserName("");
                    }
                    if (StringUtils.isNotEmpty(report.getDeparmentIds())) {
                        String[] departmentIds = report.getDeparmentIds().split(",");
                        StringBuffer stringBuffer = new StringBuffer("");
                        for (String id : departmentIds) {
                            if (StringUtils.isNotEmpty(id)) {
                                Department department = departmentRepository.findOne(Long.valueOf(id));
                                if (department != null && StringUtils.isNotEmpty(department.getName())) {
                                    stringBuffer.append(department.getName() + ",");
                                }
                            }
                        }
                        unFinshedFollowUp.setAnswer(stringBuffer.toString());
                    }
                    unFinshedFollowUps.add(unFinshedFollowUp);
                }
                //处理产品问题（投诉）
                if (Long.valueOf(serviceReport.getAnswerId()).equals(246L)) {
                    String[] str = getStrArray(report, userProfile);
                    manageProduct.add(str);
                }
                //计划进行该项工作，尚未开展
                if (Long.valueOf(serviceReport.getAnswerId()).equals(354L)) {
                    String[] str = getStrArray(report, userProfile);
                    planReport.add(str);
                }

            }
        }

        results.setManageProduct(manageProduct);
        results.setNoComplete_UnFollowUp(noComplete_UnFollowUp);
        results.setNoComplete_needFollowUp(noComplete_needFollowUp);
        results.setCompleteReport(completeReport);
        results.setComplete_needFollowUp(complete_needFollowUp);
        results.setPlanReport(planReport);

        results.setCompleteFollowUps(completeFollowUps);
        results.setUnFinshedNoFollowUps(unFinshedNoFollowUps);
        results.setUnFinshedFollowUps(unFinshedFollowUps);
        results.setNoComplete_UnableToFollowUp(noComplete_UnableToFollowUp.intValue());
        results.setNoComplete_NeedToFollowUp(noComplete_NeedToFollowUp.intValue());
        results.setComplete(complete.intValue());
        results.setComplete_NeedOthersToFollowUp(complete_NeedOthersToFollowUp.intValue());
        results.setCountPerson(noComplete_UnableToFollowUp.intValue() + noComplete_NeedToFollowUp.intValue() + complete.intValue() + complete_NeedOthersToFollowUp.intValue());
        return results;
    }

    private String getReportAnswer(Station station, Long questionId) {
        StationReport stationReport = stationReportRepository.selectReport(station.getId());
        if (stationReport == null) {
            return "";
        }
        StationColorReport colorReport = stationColorReportRepository.selectReport(stationReport.getId(), questionId);
        if (colorReport == null) {
            return "";
        }
        if (StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
            return colorReport.getAnswerOther();
        } else {
            String answerId = colorReport.getAnswerId();
            String[] ids = answerId.split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : ids) {
                QuestionAnswerOption answerOption = null;
                if (StringUtils.isNotEmpty(id)) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                }
                if (answerOption != null && answerOption.getName()!=null) {
                    if (StringUtils.isNotEmpty(answerOption.getName())) {
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
            }
            return stringBuffer.toString();
        }
    }

    private String getServiceReportAnswer(StationReport stationReport, Long questionId) {
        StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.selectQuestionOther(stationReport.getId(), questionId);
        if (serviceReport == null) {
            return "";
        }
        if (StringUtils.isNotEmpty(serviceReport.getAnswerOther())) {
            return serviceReport.getAnswerOther();
        } else {
            String answerId = serviceReport.getAnswerId();
            String[] ids = answerId.split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : ids) {
                QuestionAnswerOption answerOption = null;
                if (StringUtils.isNotEmpty(id)) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                }
                if (answerOption != null && answerOption.getName()!=null) {
                    if (StringUtils.isNotEmpty(answerOption.getName())) {
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
            }
            return stringBuffer.toString();
        }
    }

    private String[] getStrArray(StationReport report, UserProfile userProfile) {
        String[] str = new String[14];
        str[0] = report.getCreationTimeStr();
        str[1] = userProfile.getRealName();
        str[2] = report.getStation().getProvince();
        str[3] = report.getStation().getName();
        str[4] = report.getStation().getCategory();
        str[5] = report.getStation().getBrand();
        str[6] = report.getStation().getStationNum();
        str[7] = getReportAnswer(report.getStation(), 184L);
        str[8] = getReportAnswer(report.getStation(), 185L);
        str[9] = getReportAnswer(report.getStation(), 13L);
        str[10] = getReportAnswer(report.getStation(), 182L);
        str[11] = getReportAnswer(report.getStation(), 14L);
        str[12] = getServiceReportAnswer(report, 155L);
        str[13] = getServiceReportAnswer(report, 157L);
        return str;
    }

    @Autowired
    private DepartmentRepository departmentRepository;

    //筛选条件
    @Override
    public List<StationReport> getStationReport(String provinces, String brand, String category, String name,
                                                Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                                Integer serviceNum, String userName, String isFollowUp, String followType, Long userId, String userType, Boolean isCustomer,
                                                Long customerStat, Long customerType, String parintBrand, String productPosition, String stationNum, Long departmentId) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
//        builder.and(qStationReport.station.checkStation.eq(true));

        /**
         * 判断是否是经销商
         * 经销商：拿出经销商绑定的维修站ID 进行筛选
         * 内部人员：拿出绑定的省份 进行筛选
         */
        User user = userRepository.findOne(userId);
        UserProfile userProfile = userProfileRepository.findByUserId(userId);
        if (userProfile == null) {
            return null;
        }
        if (StringUtils.isNotEmpty(provinces)) {
            String[] province = provinces.split(",");
            builder.and(qStationReport.station.province.in(province));
        }
//        else {
//            List<Nation> nationList = userProfile.getNationList();
//            String[] provinceArray = new String[nationList.size()];
//            for (int i = 0; i < nationList.size(); i++) {
//                provinceArray[i] = nationList.get(i).getProvince();
//            }
//            builder.and(qStationReport.station.province.in(provinceArray));
//        }

        if (StringUtils.isNotEmpty(brand)) {
            String[] brandArray = brand.split(",");
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (int i = 0; i < brandArray.length; i++) {
                if (brandArray[i].equals("其他品牌")) {
                    orBuilder.or(qStationReport.station.otherBrand.eq(true));
                } else {
                    orBuilder.or(qStationReport.station.brand.like("%" + brandArray[i] + "%"));
                }
            }
            builder.and(orBuilder);
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qStationReport.station.stationNum.like("%" + stationNum + "%"));
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qStationReport.station.category.eq(category));
        }
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qStationReport.station.name.like("%" + name + "%"));
        }
        if (serviceType != null && serviceType != 0) {
            builder.and(qStationReport.serviceTypAnswerIds.like("%" + serviceType + "%"));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qStationReport.user.serviceNum.eq(serviceNum));
        }
        if (customerStat != null && customerStat != 0) {
            builder.and(qStationReport.station.customerStat.eq(customerStat));
        }
        if (customerType != null && customerType != 0) {
            builder.and(qStationReport.station.customerType.eq(customerType));
        }
        if (StringUtils.isNotEmpty(parintBrand)) {
            builder.and(qStationReport.station.paintBrand.like("%" + parintBrand + "%"));
        }
        if (StringUtils.isNotEmpty(productPosition)) {
            builder.and(qStationReport.station.productPosition.like("%" + productPosition + "%"));
        }
        List<Long> userIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(userName)) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            List<UserProfile> userProfiles = (List<UserProfile>) userProfileRepository.findAll();
            for (UserProfile profile : userProfiles) {
                userIds.add(profile.getUser().getId());
            }

        } else {
            if (departmentId != null && departmentId != 0) {
                if (departmentId.equals(27L)) {
                    QUser qUser = QUser.user;
                    BooleanBuilder booleanBuilder = new BooleanBuilder();
                    booleanBuilder.and(qUser.deleted.eq(false));
                    booleanBuilder.and(qUser.enabled.eq(true));
                    booleanBuilder.and(qUser.userType.eq(UserType.dealers));
                    List<User> userList = (List<User>) userRepository.findAll(booleanBuilder);
                    for (User u : userList) {
                        userIds.add(u.getId());
                    }
                } else {
                    QUserProfile qUserProfile = QUserProfile.userProfile;
                    BooleanBuilder booleanBuilder = new BooleanBuilder();
                    booleanBuilder.and(qUserProfile.deleted.eq(false));
                    booleanBuilder.and(qUserProfile.enabled.eq(true));
                    List<Department> departmentList = departmentRepository.selectParentDeparmentL(departmentId);
                    if (!departmentList.isEmpty()) {
                        List<Long> departmentIds = new ArrayList<>();
                        for (Department department : departmentList) {
                            departmentIds.add(department.getId());
                        }
                        booleanBuilder.and(qUserProfile.departmentList.any().id.in(departmentIds));
                    } else {
                        booleanBuilder.and(qUserProfile.departmentList.any().id.eq(departmentId));
                    }
                    List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                    for (UserProfile profile : userProfileList) {
                        userIds.add(profile.getUser().getId());
                    }
                }
            }
        }
        if (!userIds.isEmpty()) {
            builder.and(qStationReport.user.id.in(userIds));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qStationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qStationReport.endServiceTime.before(new Date(serviceEndTime)));
        }

        if (startTime != null && startTime != 0 && endTime != null && endTime != 0) {
            builder.and(qStationReport.creationTime.after(new Date(startTime)));
            builder.and(qStationReport.creationTime.before(new Date(endTime)));
        }

        List<StationReport> reports = (List<StationReport>) stationReportRepository.findAll(builder);
        return reports;
    }


    //todo 按照 站点 人名 品牌 统计
    @Override
    public com.ugoodtech.mdcc.core.dto.JsonResponse getServiceChart(User user, String provinces, String brandname, String stationName, String userName, String departmentId,
                                                                    Long startTime,
                                                                    Long endTime,
                                                                    Long serviceStartTime,
                                                                    Long serviceEndTime,
                                                                    String category) {
        com.ugoodtech.mdcc.core.dto.JsonResponse jsonResponse = serviceReportService.getServiceChart(user, provinces, brandname, stationName, userName, departmentId, category, startTime, endTime);
        return jsonResponse;
    }

}
